# python-resmon - Python tools for Resmon monitoring and the Circonus API
# Copyright (c) 2010 Crown coypright
# 
# This file is part of python-resmon.
# 
# python-resmon is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# 
# python-resmon is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with python-resmon.  If not, see <http://www.gnu.org/licenses/>.

import sys
from optparse import OptionParser
from circonus.api import CirconusAPI
from circonus.feed import CirconusAlertFeed
from checker import ParallelResmonChecker 
from ruleparse.loader import load
from checker.alert import *

SEV_FORMAT = {
    0: '1;37;41',
    1: '0;31',
    2: '1;31',
    3: '0;33',
    4: '1;33',
    5: '0;37',
}
FORMAT_GOOD = '0;32'

DEFAULT_RULES_FILE = 'rules.cm'

colour = True


def sev_print(sev, string, restored=False):
    """Format and print an alert string at severity sev.
    
    Behaviour depends on the value of the global `colour` flag.
    """
    if restored:
        if colour:
            print '\033[%sm%s\033[0m' % (FORMAT_GOOD, string)
        else:
            print 'Restored: %s' % (sev, string)
    else:
        if colour:
            print '\033[%sm%s\033[0m' % (SEV_FORMAT.get(sev, '0;7'), string)
        else:
            print 'Sev %d: %s' % (sev, string)


def print_colour_scheme():
    for severity in range(6):
        sev_print(severity, 'Severity %d' % severity)


def print_alert(alert):
    sev_print(alert.severity, str(alert), isinstance(alert, Restored))


if __name__ == '__main__':
    parser = OptionParser()
    parser.add_option('-c', '--colour', action='store_false', help="Disable colour output", default=sys.stdout.isatty())
    parser.add_option('-l', '--rules', help="Rules file to load", default=DEFAULT_RULES_FILE)
    parser.add_option('-s', '--scheme', action="store_true", help="Show severity colour scheme")
    parser.add_option('-1', '--current', action="store_true", help="Compute outstanding alerts only")

    options, args = parser.parse_args()

    colour = options.colour

    if options.scheme:
        print_colour_scheme()
    elif options.current:
        cc = ParallelResmonChecker()
        for a in cc.run_checks():
            print_alert(a)
    else:
        circonus_account = CirconusAPI.from_config()
        rules = load(options.rules)

        feed = CirconusAlertFeed(circonus_account, rules)
        feed.add_alert_listener(print_alert)
        feed.run()
